package com.fesine.quartz.chapter4;

import com.fesine.quartz.util.DateUtil;
import org.quartz.Calendar;
import org.quartz.impl.calendar.BaseCalendar;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @description: 自定义实现排除小时中的一些分钟
 * @author: Fesine
 * @createTime:2016/11/18 21:57
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2016/11/18 21:57
 */
public class HourlyCalender extends BaseCalendar {

    //创建0-59分钟列表
    private List excludedMinutes = new ArrayList();

    public HourlyCalender() {
        super();
    }

    //此处的日历参数是quartz中的参数
    public HourlyCalender(Calendar calendar) {
        super(calendar);
    }

    /**
     * 判断list中是否包含添加的分钟值
     * @param minute
     * @return
     */
    public boolean isMinuteExcluded(int minute) {
        Iterator iterator = excludedMinutes.iterator();
        while (iterator.hasNext()) {
            Integer excludeMinute = (Integer) iterator.next();
            if (minute == excludeMinute.intValue()) {
                return true;
            }
            continue;
        }
        return false;
    }

    public List getExcludedMinutes() {
        return excludedMinutes;
    }

    /**
     * 添加分钟值列表到排除列表中
     * @param minutes
     */
    public void setExcludedMinutes(List minutes) {
        if (minutes == null) {
            return;
        }
        excludedMinutes.addAll(minutes);
    }

    /**
     * 添加单个分钟数据到排除列表中
     * @param minute
     */
    public void setExcludedMinutes(int minute) {
        if (isMinuteExcluded(minute)) {
            return;
        }
        excludedMinutes.add(new Integer(minute));
    }

    /**
     * 获取时间戳的分钟值，并判断是否在排除列表中
     * @param timeStamp
     * @return
     */
    public boolean isTimeIncluded(long timeStamp) {
        if (super.isTimeIncluded(timeStamp)==false) {
            return false;
        }
        //将时间戳转换成java日历
        java.util.Calendar cal = DateUtil.getJavaCalendar(timeStamp);
        //获取当前日历中的分钟
        int minute = cal.get(java.util.Calendar.MINUTE);
        //判断分钟是否在排除被排除列表中，如果是则返回false否则返回true
        return !(isMinuteExcluded(minute));
    }

    public long getNextIncludedTime(long timeStamp) {
        long baseTime = super.getNextIncludedTime(timeStamp);
        if (baseTime > 0 && baseTime > timeStamp) {
            timeStamp = baseTime;
        }
        long newTimeStamp = DateUtil.buildHoliday(timeStamp);
        java.util.Calendar cal = DateUtil.getJavaCalendar(newTimeStamp);
        int minute = cal.get(java.util.Calendar.MINUTE);
        if (isMinuteExcluded(minute) == false) {
            return timeStamp;//返回原来值
        }
        while (isMinuteExcluded(minute) == true) {
            cal.add(java.util.Calendar.MINUTE, 1);//当前分钟+1
        }
        return cal.getTime().getTime();
    }



}
